<template>
  <div class="h-full w-full bg-gray-50 flex flex-col">
    <!-- 配置表单 - 100%宽度，充分利用空间 -->
    <div class="flex-1 p-6 overflow-y-auto">
      <div class="space-y-6">
        <!-- 相似性检测模式 -->
        <div class="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border border-blue-200 p-6">
          <div class="flex">
            <!-- 左侧标题 -->
            <div class="w-32 flex-shrink-0 flex items-center">
              <svg class="w-5 h-5 text-blue-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              <span class="text-base font-semibold text-gray-900">检测模式</span>
            </div>
            <!-- 右侧内容 -->
            <div class="flex-1 ml-4">
              <div class="grid grid-cols-2 gap-4">
                <div class="relative">
                  <input 
                    type="radio" 
                    id="exact" 
                    value="exact" 
                    :checked="detectionMode === 'exact'"
                    @change="() => { detectionMode = 'exact'; console.log('检测模式改为:', detectionMode.value); }"
                    class="sr-only"
                  >
                  <label 
                    for="exact" 
                    class="block p-4 border-2 rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                    :class="detectionMode === 'exact' 
                      ? 'border-blue-500 bg-blue-50 shadow-lg' 
                      : 'border-gray-200 hover:border-gray-300'"
                  >
                    <div class="flex items-start">
                      <div class="w-4 h-4 border-2 rounded-full mr-3 mt-0.5 flex items-center justify-center flex-shrink-0"
                           :class="detectionMode === 'exact' ? 'border-blue-500' : 'border-gray-300'">
                        <div v-if="detectionMode === 'exact'" class="w-2 h-2 bg-blue-500 rounded-full"></div>
                      </div>
                      <div>
                        <div class="font-semibold text-gray-900 text-base mb-1">🔍 完全一致</div>
                        <div class="text-sm text-gray-600">基于文件哈希值，100%相同</div>
                      </div>
                    </div>
                  </label>
                </div>
                
                <div class="relative">
                  <input 
                    type="radio" 
                    id="similar" 
                    value="similar" 
                    :checked="detectionMode === 'similar'"
                    @change="() => { detectionMode = 'similar'; console.log('检测模式改为:', detectionMode.value); }"
                    class="sr-only"
                  >
                  <label 
                    for="similar" 
                    class="block p-4 border-2 rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                    :class="detectionMode === 'similar' 
                      ? 'border-purple-500 bg-purple-50 shadow-lg' 
                      : 'border-gray-200 hover:border-gray-300'"
                  >
                    <div class="flex items-start">
                      <div class="w-4 h-4 border-2 rounded-full mr-3 mt-0.5 flex items-center justify-center flex-shrink-0"
                           :class="detectionMode === 'similar' ? 'border-purple-500' : 'border-gray-300'">
                        <div v-if="detectionMode === 'similar'" class="w-1 h-1 bg-purple-500 rounded-full"></div>
                      </div>
                      <div>
                        <div class="font-semibold text-gray-900 text-base mb-1">🎯 智能相似</div>
                        <div class="text-sm text-gray-600">基于内容分析，识别相似文件</div>
                      </div>
                    </div>
                  </label>
                </div>
              </div>
              
              <!-- 相似性阈值设置 -->
              <div v-if="detectionMode === 'similar'" class="mt-6 p-4 bg-white rounded-lg border border-gray-200">
                <label class="block text-base font-medium text-gray-700 mb-3">相似性阈值</label>
                <div class="flex items-center space-x-4">
                  <input 
                    type="range" 
                    :value="similarityThreshold"
                    @input="similarityThreshold = Number(($event.target as HTMLInputElement).value)"
                    min="70" 
                    max="99" 
                    step="1"
                    class="flex-1 h-2 bg-gray-200 rounded appearance-none cursor-pointer slider"
                  >
                  <span class="text-lg font-semibold text-purple-600 min-w-[3rem]">{{ similarityThreshold }}%</span>
                </div>
                <div class="flex justify-between text-sm text-gray-500 mt-2">
                  <span>70% (宽松)</span>
                  <span>99% (严格)</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 扫描模式 -->
        <div class="bg-gradient-to-r from-green-50 to-blue-50 rounded-lg border border-green-200 p-6">
          <div class="flex">
            <!-- 左侧标题 -->
            <div class="w-32 flex-shrink-0 flex items-center">
              <svg class="w-5 h-5 text-green-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
              </svg>
              <span class="text-base font-semibold text-gray-900">扫描模式</span>
            </div>
            <!-- 右侧内容 -->
            <div class="flex-1 ml-4">
              <div class="grid grid-cols-2 gap-4">
                <div class="relative">
                  <input 
                    type="radio" 
                    id="quick" 
                    value="quick" 
                    :checked="scanMode === 'quick'"
                    @change="() => { scanMode = 'quick'; console.log('扫描模式改为:', scanMode.value); }"
                    class="sr-only"
                  >
                  <label 
                    for="quick" 
                    class="block p-4 border-2 rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                    :class="scanMode === 'quick' 
                      ? 'border-green-500 bg-green-50 shadow-lg' 
                      : 'border-gray-200 hover:border-gray-300'"
                  >
                    <div class="flex items-start">
                      <div class="w-4 h-4 border-2 rounded-full mr-3 mt-0.5 flex items-center justify-center flex-shrink-0"
                           :class="scanMode === 'quick' ? 'border-green-500' : 'border-gray-300'">
                        <div v-if="scanMode === 'quick'" class="w-1 h-1 bg-green-500 rounded-full"></div>
                      </div>
                      <div>
                        <div class="font-semibold text-gray-900 text-base mb-1">⚡ 快速扫描</div>
                        <div class="text-sm text-gray-600">仅检查文件大小和名称</div>
                      </div>
                    </div>
                  </label>
                </div>
                
                <div class="relative">
                  <input 
                    type="radio" 
                    id="thorough" 
                    value="thorough" 
                    :checked="scanMode === 'thorough'"
                    @change="() => { scanMode = 'thorough'; console.log('扫描模式改为:', scanMode.value); }"
                    class="sr-only"
                  >
                  <label 
                    for="thorough" 
                    class="block p-4 border-2 rounded-lg cursor-pointer transition-all duration-200 hover:shadow-md"
                    :class="scanMode === 'thorough' 
                      ? 'border-blue-500 bg-blue-50 shadow-lg' 
                      : 'border-gray-200 hover:border-gray-300'"
                  >
                    <div class="flex items-start">
                      <div class="w-4 h-4 border-2 rounded-full mr-3 mt-0.5 flex items-center justify-center flex-shrink-0"
                           :class="scanMode === 'thorough' ? 'border-blue-500' : 'border-gray-300'">
                        <div v-if="scanMode === 'thorough'" class="w-1 h-1 bg-blue-500 rounded-full"></div>
                      </div>
                      <div>
                        <div class="font-semibold text-gray-900 text-base mb-1">🔍 深度扫描</div>
                        <div class="text-sm text-gray-600">检查文件内容和哈希值</div>
                      </div>
                    </div>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 文件类型过滤 -->
        <div class="bg-gradient-to-r from-orange-50 to-red-50 rounded-lg border border-orange-200 p-6">
          <div class="flex">
            <!-- 左侧标题 -->
            <div class="w-32 flex-shrink-0 flex items-center">
              <svg class="w-5 h-5 text-orange-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
              </svg>
              <span class="text-base font-semibold text-gray-900">文件类型过滤</span>
            </div>
            <!-- 右侧内容 -->
            <div class="flex-1 ml-4">
              <div class="grid grid-cols-2 gap-4">
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterImages" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">图片文件 {{ filterImages ? extensionDisplay('images') : '' }}</span>
                </label>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterVideos" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">视频文件 {{ filterVideos ? extensionDisplay('videos') : '' }}</span>
                </label>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterAudios" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">音频文件 {{ filterAudios ? extensionDisplay('audios') : '' }}</span>
                </label>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterDocuments" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">文档文件 {{ filterDocuments ? extensionDisplay('documents') : '' }}</span>
                </label>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterArchives" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">压缩文件 {{ filterArchives ? extensionDisplay('archives') : '' }}</span>
                </label>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="filterAll" class="w-4 h-4 text-blue-600 border-gray-300 rounded" @change="handleFilterAllChange">
                  <span class="text-base text-gray-700">全部文件类型</span>
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 扫描路径配置 -->
        <div class="bg-gradient-to-r from-indigo-50 to-purple-50 rounded-lg border border-indigo-200 p-6">
          <div class="flex">
            <!-- 左侧标题 -->
            <div class="w-32 flex-shrink-0 flex items-center">
              <svg class="w-5 h-5 text-indigo-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z"></path>
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5a2 2 0 012-2h4a2 2 0 012 2v2H8V5z"></path>
              </svg>
              <span class="text-base font-semibold text-gray-900">扫描路径配置</span>
            </div>
            <!-- 右侧内容 -->
            <div class="flex-1 ml-4">
              <div class="space-y-4">
                <div class="flex items-center space-x-3">
                  <input 
                    type="text" 
                    :value="scanPath"
                    @input="$emit('update:scanPath', ($event.target as HTMLInputElement).value)"
                    placeholder="选择要扫描的文件夹路径"
                    class="flex-1 px-4 py-3 text-base border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                  <button 
                    @click="$emit('select-directory')"
                    class="px-6 py-3 bg-blue-500 hover:bg-blue-600 text-white text-base font-medium rounded-lg transition-colors"
                  >
                    选择
                  </button>
                </div>
                <label class="flex items-center space-x-3">
                  <input type="checkbox" v-model="includeSubfolders" class="w-4 h-4 text-blue-600 border-gray-300 rounded">
                  <span class="text-base text-gray-700">包含子文件夹</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 - 使用flex布局确保位置正确 -->
    <div class="bg-white border-t border-gray-200 px-6 py-4 flex-shrink-0">
      <div class="flex justify-between items-center">
        <button 
          @click="$emit('navigate', 'home')"
          class="bg-gray-300 hover:bg-gray-400 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium transition-colors"
        >
          <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
          返回首页
        </button>
        
        <button 
          @click="startScan"
          :disabled="!scanPath"
          :class="[
            'px-6 py-2 text-sm font-medium rounded-lg transition-colors',
            scanPath 
              ? 'bg-blue-600 hover:bg-blue-700 text-white' 
              : 'bg-gray-300 text-gray-500 cursor-not-allowed'
          ]"
        >
          <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
          </svg>
          {{ scanPath ? '开始扫描' : '请先选择扫描路径' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'

// 定义props
interface Props {
  scanMode: string
  scanPath: string
  minFileSize: string
  maxFileSize: string
  hasProjectRecord?: boolean
  projectRecordInfo?: {
    totalFiles: number
    duplicateGroups: number
  }
  detectionMode: string
  similarityThreshold: number
}

const props = defineProps<Props>()

// 定义emits
const emit = defineEmits<{
  navigate: [view: string]
  'select-directory': []
  'start-scan': [options: { extensions: string[] }]
  'update:scanMode': [value: string]
  'update:scanPath': [value: string]
  'update:minFileSize': [value: string]
  'update:maxFileSize': [value: string]
  'update:detectionMode': [value: string]
  'update:similarityThreshold': [value: number]
}>()

// 检测模式
const detectionMode = ref<'exact' | 'similar'>(props.detectionMode as 'exact' | 'similar' || 'exact')
const similarityThreshold = ref(props.similarityThreshold || 90)

// 扫描模式 - 默认选择深度扫描
const scanMode = ref<'quick' | 'thorough'>(props.scanMode as 'quick' | 'thorough' || 'thorough')

// 文件类型过滤
const filterImages = ref(false)
const filterVideos = ref(false)
const filterDocuments = ref(false)
const filterArchives = ref(false)
const filterAudios = ref(false)
const filterAll = ref(true)

// 包含子文件夹选项
const includeSubfolders = ref(true)

const fileTypeExtensions = ref<{ [key: string]: string }>({
  images: '',
  videos: '',
  audios: '',
  documents: '',
  archives: ''
})

const defaultFileTypes = {
  images: 'jpg,jpeg,png,gif,bmp,webp',
  videos: 'mp4,avi,mov,wmv,flv,mkv',
  audios: 'mp3,wav,flac,aac,wma',
  documents: 'doc,docx,xls,xlsx,pdf,txt,rtf',
  archives: 'zip,rar,7z'
}

onMounted(() => {
  const saved = localStorage.getItem('fileTypeSettings')
  if (saved) {
    try {
      const parsed = JSON.parse(saved)
      // 确保所有类型都有值，如果没有则使用默认值
      fileTypeExtensions.value = {
        images: parsed.images || defaultFileTypes.images,
        videos: parsed.videos || defaultFileTypes.videos,
        audios: parsed.audios || defaultFileTypes.audios,
        documents: parsed.documents || defaultFileTypes.documents,
        archives: parsed.archives || defaultFileTypes.archives
      }
    } catch (e) {
      console.error('解析保存的文件类型设置失败:', e)
      fileTypeExtensions.value = { ...defaultFileTypes }
    }
  } else {
    fileTypeExtensions.value = { ...defaultFileTypes }
  }
  
  console.log('初始化后的文件类型扩展名:', fileTypeExtensions.value)
})

watch(filterAll, (newValue) => {
  if (newValue) {
    // 勾选全部时，取消所有单独选项
    filterImages.value = false
    filterVideos.value = false
    filterAudios.value = false
    filterDocuments.value = false
    filterArchives.value = false
  }
})

watch([filterImages, filterVideos, filterAudios, filterDocuments, filterArchives], () => {
  const anyChecked = filterImages.value || filterVideos.value || filterAudios.value || filterDocuments.value || filterArchives.value
  
  if (anyChecked) {
    // 当有任何单独选项被选中时，取消"全部"
    filterAll.value = false
  } else {
    // 当所有单独选项都未选中时，自动选中"全部"且不能取消
    filterAll.value = true
  }
})

// 监听"全部"的取消操作，如果其他选项都未选中则阻止取消
const handleFilterAllChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  const anyChecked = filterImages.value || filterVideos.value || filterAudios.value || filterDocuments.value || filterArchives.value
  
  if (!target.checked && !anyChecked) {
    // 如果尝试取消"全部"且没有其他选项被选中，阻止取消
    event.preventDefault()
    filterAll.value = true
  }
}

// 监听检测模式变化
watch(detectionMode, (newValue) => {
  emit('update:detectionMode', newValue)
})

// 监听扫描模式变化
watch(scanMode, (newValue) => {
  emit('update:scanMode', newValue)
})

// 监听相似性阈值变化
watch(similarityThreshold, (newValue) => {
  emit('update:similarityThreshold', newValue)
})

const extensionDisplay = (type: string): string => {
  return fileTypeExtensions.value[type] ? `(${fileTypeExtensions.value[type]})` : '';
}

const startScan = () => {
  const selectedExtensions: string[] = []
  
  console.log('开始扫描，当前选择状态:', {
    filterAll: filterAll.value,
    filterImages: filterImages.value,
    filterVideos: filterVideos.value,
    filterAudios: filterAudios.value,
    filterDocuments: filterDocuments.value,
    filterArchives: filterArchives.value
  })
  
  if (filterAll.value) {
    // 当选择"全部文件类型"时，传递空数组表示扫描所有文件类型
    // 后端收到空数组时会扫描所有文件，不限制扩展名
    console.log('选择"全部文件类型"，传递空数组到后端')
  } else {
    // 当选择特定文件类型时，只传递选中的扩展名
    if (filterImages.value) {
      const imageExts = fileTypeExtensions.value.images.split(',').filter(ext => ext.trim())
      selectedExtensions.push(...imageExts)
      console.log('选择图片文件，扩展名:', imageExts)
    }
    if (filterVideos.value) {
      const videoExts = fileTypeExtensions.value.videos.split(',').filter(ext => ext.trim())
      selectedExtensions.push(...videoExts)
      console.log('选择视频文件，扩展名:', videoExts)
    }
    if (filterAudios.value) {
      const audioExts = fileTypeExtensions.value.audios.split(',').filter(ext => ext.trim())
      selectedExtensions.push(...audioExts)
      console.log('选择音频文件，扩展名:', audioExts)
    }
    if (filterDocuments.value) {
      const docExts = fileTypeExtensions.value.documents.split(',').filter(ext => ext.trim())
      selectedExtensions.push(...docExts)
      console.log('选择文档文件，扩展名:', docExts)
    }
    if (filterArchives.value) {
      const archiveExts = fileTypeExtensions.value.archives.split(',').filter(ext => ext.trim())
      selectedExtensions.push(...archiveExts)
      console.log('选择压缩文件，扩展名:', archiveExts)
    }
  }
  
  console.log('最终发送到后端的扩展名列表:', selectedExtensions)
  emit('start-scan', { extensions: selectedExtensions })
}

// 暴露给父组件
defineExpose({
  detectionMode,
  similarityThreshold
})
</script>

<style scoped>
.slider::-webkit-slider-thumb {
  appearance: none;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background: #8b5cf6;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.slider::-moz-range-thumb {
  height: 20px;
  width: 20px;
  border-radius: 50%;
  background: #8b5cf6;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}
</style>